<template>
    <div class="common-layout">
        <el-container>
            <el-container>
                <el-header height="500px">
                    <!-- 进行中的任务 -->
                    <a-card class="box-card" :tab-list="tabList" :active-tab-key="key"
                            @tabChange="key => onTabChange(key)">
                            <div v-if="key === 'process'" class="card-container">
                                <div v-for="row in rowCount" :key="row">
                                    <el-row :gutter="30">
                                        <div v-for="item in rowItems(row)" :key="item">
                                            <el-col :span="6">
                                                <el-card class="card-item">
                                                    <el-row  class="row-item">
                                                        <el-col>
                                                            <div class="spinner-box">
                                                                <div class="circle-border">
                                                                    <div class="circle-core"> 
                                                                     
                                                                    </div>
                                                                </div>  
                                                            </div>
                                                        </el-col>
                                        
                                                    </el-row>
                                                    <el-row>
                                                        <el-col>
                                                            <el-space wrap>
                                                                <el-tag>{{ item.test_infer }}</el-tag>
                                                                <el-tag>{{ item.test_environment }}</el-tag>
                                                            </el-space>
                                                            <el-row style="margin-top:10px">
                                                                <el-tooltip :content="item.test_purpose" placement="top">
                                                                <span class="ellipsis-tooltip">{{ item.test_purpose }}</span>
                                                                </el-tooltip>    
                                                            </el-row>
                                                        </el-col>
                                                    </el-row>
                                                </el-card>
                                            </el-col>
                                        </div>
                                    </el-row>
                                </div>
                            
                            <!-- <div v-for="task in inProgress" :key="task.taskid" class="card-item">
                                <el-space wrap>
                                <el-card style="width: 320px; margin-bottom: 20px; height: 400px;">
                                    <el-row  style="padding: 0 40px; background-color: #37474f;">
                                        <el-col>
                                            <div class="spinner-box">
                                                <div class="circle-border">
                                                    <div class="circle-core">    
                                                    </div>
                                                </div>  
                                            </div>
                                        </el-col>
                                        
                                    </el-row>
                                    <el-row style="padding: 15px 40px;">
                                        <el-col>
                                                <el-row style="height: 50px;" >
                                                    <el-tooltip :content="task.test_purpose" placement="top">
                                                        <span class="ellipsis-tooltip">{{  task.test_purpose }}</span>
                                                    </el-tooltip>    
                                                </el-row>
                                                <el-row><el-tag>{{ task.product_name }}</el-tag></el-row>
                                                <el-row style="margin-top: 10px;"><el-tag>{{ task.test_infer }}</el-tag></el-row>
                                                <el-row style="margin-top: 10px;"><el-tag>{{ task.test_environment }}</el-tag></el-row>
                                        </el-col>
                                    </el-row>
                                    
                                </el-card>
                            </el-space>
                            </div> -->
                        </div>
                        <div v-else>
                            <!-- 待测试任务 -->
                            <div v-for="task in awaitTasks" :key="task.taskid">
                                <el-card style="margin: 20px; border-color: #ecf5ff;">
                                    <el-descriptions :title="task.test_purpose" :column="3" border>
                                        <el-descriptions-item label="状态">
                                            <template v-if="task.test_status === '终止'">
                                                <el-tag type="danger" effect="dark">{{ task.test_status }}</el-tag>
                                            </template>
                                            <template v-else>
                                                <el-tag type="info" effect="dark">{{ task.test_status }}</el-tag>
                                            </template>
                                        </el-descriptions-item>
                                        <el-descriptions-item label="产品"><el-tag effect="dark">{{ task.product_name
                                        }}</el-tag></el-descriptions-item>
                                        <el-descriptions-item label="申请时间">{{ task.create_time }}</el-descriptions-item>
                                        <el-descriptions-item label="测试环境"><el-tag effect="dark">{{ task.test_environment
                                        }}</el-tag></el-descriptions-item>
                                        <el-descriptions-item label="推理"><el-tag effect="dark">{{ task.test_infer
                                        }}</el-tag></el-descriptions-item>
                                    </el-descriptions>
                                </el-card>
                            </div>
                        </div>
                    </a-card>
                </el-header>
                <el-main>
                    <!-- 服务器资源展示 -->
                    <a-card class="box-card" style="width: 100%;height: 429px;" :tab-list="serverList"
                        :active-tab-key="serverKey" @tabChange="serverKey => onServerChange(serverKey)">
                        <ChartLine ref="serverChart" width="auto" :height="1000" />
                    </a-card>
                </el-main>
            </el-container>
            <el-aside width="400px">
                <!-- 历史任务展示 -->
                <a-card style="height: 950px; overflow-y: auto;" title="排队任务">
                    <el-timeline style="padding: 20px;">
                        <el-timeline-item v-for="(task, index) in queueTasks" :key="index" type="primary"
                            :timestamp="task.create_time" placement="top" center>
                            <el-card shadow="hover" style="border-radius: 10px; width: 320px;">
                                <el-row :gutter="10">
                                    <el-col :span="3"><el-tag effect="dark" >
                                    {{ index + 1 }}</el-tag></el-col>
                                    <el-col :span="17" class="ellipsis-tooltip">{{ task.test_purpose }}</el-col>
                                    <el-col :span="4"><el-button type="primary" size="small" link @click="showDetail(task)">置顶</el-button></el-col>
                                </el-row> 
                            </el-card>
                        </el-timeline-item>
                    </el-timeline>
                </a-card>
            </el-aside>
        </el-container>
    </div>

    <!-- 历史任务的详细信息 -->
    <el-drawer v-model="detailVisible" title="测试任务详情" size="50%">
        <el-descriptions :column="1" border>
            <el-descriptions-item label="测试目的">{{ taskDetail.test_purpose }}</el-descriptions-item>
            <el-descriptions-item label="预期结果">{{ taskDetail.expected_result }}</el-descriptions-item>
            <el-descriptions-item label="状态"><el-tag :type="getTagType(taskDetail.test_status)">{{ taskDetail.test_status }}</el-tag></el-descriptions-item>
            <el-descriptions-item label="测试环境"><el-tag>{{ taskDetail.test_environment }}</el-tag></el-descriptions-item>
            <el-descriptions-item label="产品"><el-tag>{{ taskDetail.product_name }}</el-tag></el-descriptions-item>
            <el-descriptions-item label="推理"><el-tag>{{ taskDetail.test_infer }}</el-tag></el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ taskDetail.create_time }}</el-descriptions-item>
            <el-descriptions-item label="完成时间">{{ taskDetail.finish_time }}</el-descriptions-item>
            <el-descriptions-item label="数据路径">{{ taskDetail.test_data }}</el-descriptions-item>
            <el-descriptions-item label="svn">{{ taskDetail.svn }}</el-descriptions-item>
        </el-descriptions>
    </el-drawer>
</template>

<script lang="ts" setup>
import { TaskService } from '@/api/task';
import appStore from '@/pinia';
import { storeToRefs } from 'pinia';
import { h, ref } from 'vue';

const spacer = h(ElDivider, { direction: 'vertical' })
const inProgress = ref()
const historyTasks = ref()
const queueTasks = ref()
// const { username } = storeToRefs(appStore.userModule);
const { socketMessage } = storeToRefs(appStore.socketModule);
const cpuGauge = ref()
const gpuGauge = ref()
const memoryGauge = ref()
const serverChart = ref()
const detailVisible = ref(false)
const taskDetail = ref()

const showDetail = (data : any) => {
    taskDetail.value = data;
    detailVisible.value = true;
}

const tabList = [
    {
        key: 'process',
        tab: '进行中的任务',
    },
    {
        key: 'next',
        tab: '待测试任务',
    }
]
const key = ref('process')

const serverList = [
    {
        key: 'wuhan',
        tab: '武汉服务器',
        ip:'192.168.31.255'
    },
    {
        key: 'T4',
        tab: 'T4服务器',
        ip:'192.168.0.160'
    },
    {
        key: 'jiqun',
        tab: '集群',
        ip:'192.168.0.511'
    }
] as any
const serverKey = ref('wuhan')
const serverIp = ref('192.168.31.255')


const onTabChange = (value: string) => {
    key.value = value;
};

const onServerChange = (value: string) => {
    serverKey.value = value;
    const server = serverList.find((server: { key: string; }) => server.key === value);
    serverIp.value = server?.ip;
    cpuGauge.value.setOption(0)
    gpuGauge.value.setOption(0)
    memoryGauge.value.setOption(0)   
};


const itemsPerRow = 5
const rowCount = ref()
const getProcessTasks = async () => {
    try {
        const res = await TaskService.getTasksByStatus("进行中")
        if (res.data.length != 0)  {
            inProgress.value = res.data
            const result = computed(() => Math.ceil(inProgress.value.length / itemsPerRow));
            rowCount.value = result.value
        }
    } catch (error) {
        window.console.error(error)
    }
}


const rowItems = (row : number) => {
    const startIndex = (row - 1) * itemsPerRow
    const endIndex = startIndex + itemsPerRow
    return inProgress.value.slice(startIndex, endIndex);
}

const getHistoryTasks = async () => {
    try {
        const res = await TaskService.getHistoryTasks()
        if ( res.data.length != 0) {
            historyTasks.value = res.data
            historyTasks.value = historyTasks.value.slice().reverse();
        }
    } catch (error) {
        window.console.error(error)
    }
}

const awaitTasks = ref()
const getAwaitTasks = async () => {
    try {
        const res = await TaskService.getAwaitTasks()
        if ( res.data.length != 0) {
            awaitTasks.value = res.data
            queueTasks.value = res.data.filter((t: { test_status: string; }) => t.test_status == "排队中")
        }
    } catch (error) {
        window.console.error(error)
    }
    
}

const getTagType = (testStatus: string) => {
    return testStatus === '通过' ? 'success' : 'danger';
}

const receiveMessage = (data: any) => {
    if (cpuGauge.value != null && data.client === serverIp.value) {
        cpuGauge.value.setOption(data.gpuName)
        gpuGauge.value.setOption(data.temperature)
        memoryGauge.value.setOption(data.utilization)   
    }
}

onMounted(() => {
    //appStore.socketModule.connectSocket()
    getProcessTasks();
    getHistoryTasks();
    getAwaitTasks();
})

watch(socketMessage, (newData) => {
    receiveMessage(newData);
})

// onBeforeUnmount(() => {
//     appStore.socketModule.closeSocket();
// })

</script>

<style lang="scss" scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  margin-top: 10px;
  margin-left: 30px;
  overflow: hidden;
}

.card-item {
    width: 250px; 
    margin-bottom: 20px; 
    height: 350px;
    padding: 0%;
    border-radius: 8px;
}

.row-item {
    //background-color: #37474f;
    border-radius: 8px;
    margin-bottom: 10px;
}

.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}

.box-card {
    overflow-y: auto;
    width: 100%; 
    height: 500px;
}

::v-deep .ant-card-body {
    padding: 0 !important;
}
::v-deep td.el-descriptions__cell.el-descriptions__label.is-bordered-label {
    width: 150px !important;
}

.ellipsis-tooltip {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

@keyframes spin {
  from {
    transform: rotate(0);
  }
  to{
    transform: rotate(359deg);
  }
}
 
/* GRID STYLING */
 
* {
  box-sizing: border-box;
}
 
body {
  min-height: 100vh;
  background-color: #37474f;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  align-items: flex-start;
}
 
.spinner-box {
  width: 200px;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: transparent;
}
 
/* SPINNING CIRCLE */
 
.circle-border {
  width: 150px;
  height: 150px;
  padding: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  background: rgb(63,249,220);
  //background: linear-gradient(0deg, rgba(63,249,220, 0.1) 33%, rgb(63,249,220) 100%);
  background: linear-gradient(0deg, rgba(25, 181, 254, 0.1) 33%, rgb(25, 181, 254) 100%);
  animation: spin .8s linear 0s infinite;
}
 
.circle-core {
  width: 100%;
  height: 100%;
  //background-color: #37474f;
  background-color: white;
  border-radius: 50%;
}

</style>